import 'dart:async';

import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import '../../../../service/HttpsClient.dart';

class RegisterStepTwoController extends GetxController {
  //TODO: Implement RegisterStepTwoController
  final TextEditingController firstField = TextEditingController();
  HttpsClient httpsClient = HttpsClient();
  String tel = Get.arguments['tel'];
  RxInt seconds = 10.obs; // 倒计时秒数

  // 验证手机号
  Future<bool> validateCode() async {
    var response = await httpsClient.post(
      'api/validateCode',
      data: {'tel': tel, "code": firstField.text},
    );
    print(response);
    if (response['success'] == true) {
      return true;
    }
    return false;
  }

  // 开始倒计时
  void startDownCount() {
    // 开启定时器
    if (seconds.value > 0) {
      Timer.periodic(const Duration(milliseconds: 1000), (Timer timer) {
        if (seconds.value > 0) {
          seconds.value--;
        } else {
          timer.cancel();
        }
       
      });
    } 
     update(); // 更新UI
  }

// 重新发送验证码
  Future<bool> sendCode(String tel) async {
    var response = await httpsClient.post('api/sendCode', data: {'tel': tel});
    print(response);
    if (response != null) {
      if (response['success'] == true) {
        // 测试期间，避免手动输入验证码，正式环境下不需要这行代码也可以粘贴
        Clipboard.setData(ClipboardData(text: response['code']));
        seconds.value = 10; // 重置倒计时
        startDownCount(); // 开始倒计时
        return true;
      } 
      
      return false;
    }
    return false;
  }

  @override
  void onInit() {
    super.onInit();
    startDownCount(); // 开始倒计时
  }

  @override
  void onClose() {
    super.onClose();
  }
}
